package com.music.players;

import com.music.MusicManager;
import java.io.File;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;
import javazoom.jlgui.basicplayer.BasicPlayerListener;

/**
 * @author sad
 */
public class Mp3Player2 implements IPlayer {

    private BasicPlayer player;
    private final String path;
    private final BasicPlayerListener listener;

    public Mp3Player2(String path, BasicPlayerListener listener) throws BasicPlayerException {
        this.path = path;
        this.listener = listener;
    }

    public BasicPlayer getPlayer() {
        return player;
    }

    @Override
    public void play() {
        try {
            player = new BasicPlayer();
            player.addBasicPlayerListener(listener);
            player.open(new File(path));
            player.play();
            if (MusicManager.getInstance().isMuted()) {
                player.setGain(0.0);
            } else {
                player.setGain(1.0);
            }
        } catch (BasicPlayerException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void stop() {
        if (player != null) {
            try {
                player.stop();
                player = null;
            } catch (BasicPlayerException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void close() {
        if (player != null) {
            try {
                player.stop();
                player = null;
            } catch (BasicPlayerException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public PlayerStatus getStatus() {
        if (player != null) {
            if (player.getStatus() == BasicPlayer.PLAYING) {
                return PlayerStatus.Play;
            } else {
                return PlayerStatus.Stop;
            }
        }
        return PlayerStatus.Stop;
    }

    @Override
    public void mute(boolean mute) {
        try {
            player.setGain(mute ? 0.0f : 1.0f);
        } catch (BasicPlayerException ex) {
        }
    }
}
